package gov.pbc.nn.kjgl.archive.dao;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.model.RoleMember;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;

import gov.pbc.nn.core.bdf.service.DeptService;
import gov.pbc.nn.core.dao.AbstractHibernateDao;
import gov.pbc.nn.core.dao.PbcnnCoreHibernateDao;
import gov.pbc.nn.kjgl.entity.Archives;
import gov.pbc.nn.kjgl.entity.ArchivesContent;
import gov.pbc.nn.kjgl.entity.ArchivesMember;
import gov.pbc.nn.kjgl.software.dao.KjkShJdbcDao;

@Repository
public class ArchivesDao extends AbstractHibernateDao {

	@Resource(name=PbcnnCoreHibernateDao.BEAN_ID)
	private PbcnnCoreHibernateDao pbcnn;
	@Autowired
	private KjkShJdbcDao kjkShJdbcDao;
	@Autowired
	@Qualifier(DeptService.BEAN_ID)
	private DeptService deptService;
	
	
	/**
	 * 获取一级档案
	 * 
	 * @return
	 */
	public List<Archives> getArchives() {
		String hql = "from Archives where invalid=false and parentId is null";
		List<Archives> ls = this.query(hql);
		if (ls != null) {
			return ls;
		}
		return null;
	}

	/**
	 * 获取二级档案
	 * 
	 * @param parentId
	 * @return
	 */
	public List<Archives> getArchivesByParentId(String parentId) {
		String hql = "from Archives where parentId=:parentId and invalid=false";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("parentId", parentId);
		List<Archives> ls = this.query(hql, map);
		if (ls != null) {
			return ls;
		}
		return null;
	}

	/**
	 * 档案维护
	 * 
	 * @param archives
	 */
	public void saveArchives(Collection<Archives> archives) {
		for (Archives arc : archives) {
			EntityState state = EntityUtils.getState(arc);
			if (state.equals(EntityState.NEW)) {
				this.save(arc);
			} else if (state.equals(EntityState.DELETED)) {
				this.delete(arc);
			}
			if (arc.getChildren() != null) {
				Archives[] arcs = new Archives[arc.getChildren().size()];
				saveArchives(Arrays.asList(arc.getChildren().toArray(arcs)));
			}
		}
	}

	/**
	 * 判断名称是否重复
	 * 
	 * @param name
	 * @param type
	 * @return
	 */
	public boolean checkName(String name, int type, String oneId) {
		if (type == 1) {
			String hql = "select count(*) from Archives where invalid=false and name=:name";
			Map<String, Object> parameterMap = new HashMap<String, Object>();
			parameterMap.put("name", name);
			if (this.queryForInt(hql, parameterMap) > 0) {
				return false;
			}
			return true;
		} else if (type == 2) {
			String hqls = "select count(*) from Archives where invalid=false and name=:name and parentId=:parentId";
			Map<String, Object> parameterMaps = new HashMap<String, Object>();
			parameterMaps.put("name", name);
			parameterMaps.put("parentId", oneId);
			if (this.queryForInt(hqls, parameterMaps) > 0) {
				return false;
			}
			return true;
		}
		return false;
	}

	/**
	 * 通过parentId获取子节点数
	 * 
	 * @param parentId
	 * @return
	 */
	public int countChildren(String parentId) {
		String hql = "select count(*) from Archives where parentId = :parentId and invalid=false";
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("parentId", parentId);
		return this.queryForInt(hql, parameterMap);
	}

	/**
	 * 添加档案人员关联关系
	 * 
	 * @param ids
	 * @param archivesId
	 * @param type
	 */
	public void insert(Collection<String> ids, String archivesId, int type) {
		if (ids != null) {
			for (String id : ids) {
				ArchivesMember am;
				am = new ArchivesMember();
				am.setArchivesId(archivesId);
				am.setMemberId(id);
				am.setType(type);
				if(type==0){
					am.setDeptName(deptService.loadDeptById(id).getName());
				}else{
					am.setCname(this.getCnameByMamberId(id));
					am.setDeptName((String)kjkShJdbcDao.getHld(id).get(0).get("name"));
				}
				this.save(am);
			}
		}
	}

	/**
	 * 通过archivesId与type获取ArchivesMember
	 * 
	 * @param archivesId
	 * @return
	 */
	public void getMemberIdByArchivesId(Page<ArchivesMember> page,Criteria criteria,
			String archivesId, int type) {
		DetachedCriteria query = this.buildDetachedCriteria(criteria, ArchivesMember.class);
//		DetachedCriteria query = DetachedCriteria.forClass(ArchivesMember.class);
		query.add(Restrictions.eq("archivesId", archivesId));
		query.add(Restrictions.or(Restrictions.eq("invalid", false),Restrictions.isNull("invalid")));
		query.add(Restrictions.eq("type", type));
		this.pagingQuery(page, query);
	}

	/**
	 * 通过id删除档案人员关联关系
	 * 
	 * @param id
	 */
	public void deleteArchivesMemberById(String id) {
		this.delete(id, ArchivesMember.class);
	}

	/**
	 * 根据roleName获取RoleId
	 * 
	 * @param roleName
	 * @return
	 */
	public String getRoleId(String roleName) {
		String hql = "select id from Role where name=:roleName";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("roleName", roleName);
		List<String> ls = pbcnn.query(hql, map);
		return ls.isEmpty() ? null : ls.get(0);
	}

	/**
	 * 通过memberId获取RoleMemberId
	 * 
	 * @param memberId
	 * @param type
	 * @return
	 */
	public String getRoleMemberId(String memberId, int type) {
		String hql = "";
		if (type == 0) {
			hql = "select id from RoleMember where deptId=:memberId";
		} else {
			hql = "select id from RoleMember where username=:memberId";
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("memberId", memberId);
		List<String> ls = pbcnn.query(hql, map);
		return ls.isEmpty() ? null : ls.get(0);
	}

	/**
	 * 获取RoleMember有几条数据
	 * 
	 * @param roleId
	 * @param memberId
	 * @param type
	 * @return
	 */
	public int getRoleMemberCount(String roleId, String memberId, int type) {
		String hql = "";
		if (type == 0) {
			hql = "select count(*) from " + RoleMember.class.getName()
					+ " where deptId=:memberId and roleId=:roleId";
		} else if (type == 1) {
			hql = "select count(*) from " + RoleMember.class.getName()
					+ " where username=:memberId and roleId=:roleId";
		} else if (type == 2) {
			hql = "select count(*) from " + RoleMember.class.getName()
					+ " where username=:memberId and roleId=:roleId";
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("roleId", roleId);
		map.put("memberId", memberId);
		return pbcnn.queryForInt(hql, map);

	}

	/**
	 * 根据memberId查询对应档案关系数量
	 * 
	 * @param memberId
	 * @return
	 */
	public boolean checkArchivesMemberByMemberId(String memberId) {
		String hql = "select count(*) from ArchivesMember where invalid =false and memberId=:memberId";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("memberId", memberId);
		int count = this.queryForInt(hql, map);
		if (count > 1) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 根据archivesId得到mamberId
	 * 
	 * @param archivesId
	 * @return
	 */
	public List<String> getMamberIdByArchives(String archivesId) {
		List<String> value = new ArrayList<String>();
		Map<String, Object> map = new HashMap<String, Object>();
		String hql = "select memberId from ArchivesMember where invalid=false and archivesId=:archivesId";
		map.put("archivesId", archivesId);
		List<String> midlist = this.query(hql, map);

		String hqls = "select id from " + RoleMember.class.getName()
				+ " where deptId=:id or username=:id";
		for (String id : midlist) {
			Map<String, Object> maps = new HashMap<String, Object>();
			maps.put("id", id);
			List<String> idlist = pbcnn.query(hqls, maps);
			for (String ids : idlist) {
				value.add(ids);
			}
		}
		return value;

	}

	/**
	 * 删除树节点时，删除对应树节点下的相关数据
	 * 
	 * @param archivesId
	 * @throws IOException
	 */
	public void deleteArchivesSon(String archivesId) throws IOException {
		// 根据档案ID删除档案人员关系
		Map<String, Object> map = new HashMap<String, Object>();
		String hql = "from ArchivesMember where invalid =false and archivesId=:archivesId";
		map.put("archivesId", archivesId);
		List<ArchivesMember> amlist = this.query(hql, map);

		for (ArchivesMember am : amlist) {
			this.delete(am);
		}
		// 根据档案ID删除档案内容
		hql = "from ArchivesContent where invalid =false and archivesId=:archivesId";
		map = new HashMap<String, Object>();
		map.put("archivesId", archivesId);
		List<ArchivesContent> aclist = this.query(hql, map);
		ArchivesInputDao aid = ContextHolder.getApplicationContext().getBean(
				ArchivesInputDao.class);
		for (ArchivesContent ac : aclist) {
			aid.delArchivesContent(ac);
		}
		// 删除当前档案
		this.delete(archivesId, Archives.class);
	}

	/**
	 * 根据mamberId查询用户的cname
	 * 
	 * @param mamberId
	 * @return
	 */
	public String getCnameByMamberId(String mamberId) {
		String hql = "select cname from User where username=:mamberId";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("mamberId", mamberId);
		List<String> ls = pbcnn.query(hql, map);
		if (ls != null && !ls.isEmpty()) {
			return ls.get(0);
		}
		return null;
	}
}
